#include "app_message.h"
#include "log/log.h"
#include "cJSON/cJSON.h"
#include "app_common.h"
#include "string.h"
#include "stdlib.h"

// json格式: {"conn_type": 1, "id": "5858", "msg": "61626364"} ==> chars: "124xxabcd"

int app_message_JsonToChars(char *json, char *chars_buf, int buf_size)
{
    // 解析json数据
    cJSON *root = cJSON_Parse(json);
    if (root == NULL)
    {
        log_error("cJSON_Parse error");
        return -1;
    }
    // 获取conn_type
    cJSON *conn_type = cJSON_GetObjectItem(root, "conn_type");
    chars_buf[0] = conn_type->valueint;
    // 获取id和msg
    char *id_hex_str = cJSON_GetObjectItem(root, "id")->valuestring;
    char *msg_hex_str = cJSON_GetObjectItem(root, "msg")->valuestring;
    // 将id和msg从十六进制字符串转换成字符数组
    int id_len = 0;
    int msg_len = 0;
    char *id_str = app_common_hexStr2Chars(id_hex_str, &id_len);
    char *msg_str = app_common_hexStr2Chars(msg_hex_str, &msg_len);
    // 检查长度
    int len = id_len + msg_len + 3;
    if (len > buf_size)
    {
        log_error("数据的长度超过缓冲区大小");
        return -1;
    }

    chars_buf[1] = id_len;
    chars_buf[2] = msg_len;
    memcpy(chars_buf + 3, id_str, id_len);
    memcpy(chars_buf + 3 + id_len, msg_str, msg_len);
    // 释放空间
    cJSON_Delete(root);
    free(id_str);
    free(msg_str);
    return len;
}

char *app_message_CharsToJson(char *chars_buf, int chars_len)
{
    // chars: "124xxabcd" ==>  {"conn_type": 1, "id": "5858", "msg": "61626364"}

    // 创建JSON对象
    cJSON *root = cJSON_CreateObject();
    // 提取字符串中的数据
    char conn_type = chars_buf[0];
    int id_len = chars_buf[1];
    int msg_len = chars_buf[2];
    // 添加到JSON对象中
    cJSON_AddNumberToObject(root, "conn_type", conn_type);
    // 将id和msg拷贝到临时变量中
    char id_chars[id_len];
    memcpy(id_chars, chars_buf + 3, id_len);
    char msg_chars[msg_len];
    memcpy(msg_chars, chars_buf + 3 + id_len, msg_len);
    // 将字符数组转换为16进制字符串
    char *id_hex_str = app_common_chars2Hex(id_chars, id_len);
    char *msg_hex_str = app_common_chars2Hex(msg_chars, msg_len);
    cJSON_AddStringToObject(root, "id", id_hex_str);
    cJSON_AddStringToObject(root, "msg", msg_hex_str);
    // 打印出json串
    char *json_str = cJSON_PrintUnformatted(root);
    // 释放内存
    cJSON_Delete(root);
    free(id_hex_str);
    free(msg_hex_str);
    return json_str;
}
